var net = require("net");

var chatServer = net.createServer(),
	clientList = []	;

chatServer.on("connection", function(client){
	client.name = client.remoteAddress + ":" + client.remotePort;
	client.write("Hi! " + client.name + "!\n");
	clientList.push(client);
	console.log("[INFO]" + client.name + " joined");

	client.on('data', function(data){
		broadCast(data, client);
	});

	// client.write("Bye!\n");

	client.on('end', function() {
		console.log("[INFO]" + client.name + " quit");
		clientList.splice(clientList.indexOf(client), 1);
	})

	client.on('error', function (err) {
		console.log("[ERROR]" + err);
	})
})

function broadCast(message, client) {
	var cleanup = [];
	for(var i = 0; i < clientList.length; i++) {
		if (client !== clientList[i]) {
			if (clientList[i].writable) {
				clientList[i].write(new Date() + "\t" + client.name + " says : " + message);
			} else {
				console.log("[WARNING]" + clientList[i] + " un-writable!!!")
				cleanup.push(clientList[i]);
				clientList[i].destroy();
			}
		}
	}

	for (var i = 0; i < cleanup.length; i++) {
		console.log("[INFO]" + clientList[i] + " removed!!!");
		clientList.splice(clientList.indexOf(cleanup[i]), 1);
	}
}

chatServer.listen(9000);
console.log("Chat server started...")